package ru.mera.aaclog.dbdao;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 * @version 1.0 23/03/2013
 * @author anavdeev
 */
public class GenericDAO<ROW> implements Serializable {
    
    private EntityManager em;

    public GenericDAO(EntityManager em) {
        this.em = em;
    }

    public List<ROW> get(String query) {
        List<ROW> rows = new ArrayList<ROW>();
        try {
            rows = em.createNamedQuery(query).getResultList();
        } catch (Exception e) {
            Logger.getLogger(GenericDAO.class.getName()).log(Level.SEVERE, query, e);
        }
        return rows;
    }

    public ROW getSingle(String queryStr, Object ... params) {
        List<ROW> row = get(queryStr, params);
        return row.size() > 0 ? row.get(0) : null;
    }
    
    public List<ROW> get(String queryStr, Object ... params) {
        List<ROW> rows = null;
        try {
            Query query = em.createNamedQuery(queryStr);
            for (int i = 0; i < params.length; i++) {
                query.setParameter(i+1, params[i]);
            }
            rows = query.getResultList();
        } catch (Exception e) {
            Logger.getLogger(GenericDAO.class.getName()).log(Level.SEVERE, queryStr, e);
        }
        if (rows == null) {
            rows = new ArrayList<ROW>();
        }
        return rows;
    }

    public boolean insert(ROW row) {
        try {
            em.getTransaction().begin();
            em.persist(row);
            em.getTransaction().commit();
            //em.refresh(table); // get state from DB
            return true;
        } catch (Exception e) {
            Logger.getLogger(GenericDAO.class.getName()).log(Level.SEVERE, row.toString(), e);
        }
        return false;
    }
    
    public void delete(ROW row) {
        try {
            em.getTransaction().begin();
            em.remove(em.merge(row));
            em.getTransaction().commit();
        } catch (Exception e) {
            Logger.getLogger(GenericDAO.class.getName()).log(Level.SEVERE, row.toString(), e);
        }
    }
}
